import TagGroup from '@/components/TagGroup';
import { listCuesIndustry } from '@/services/api/api-cues-industry';
import { saveCuesSubmit } from '@/services/api/api-cues-submit';
import {
  CheckCircleTwoTone,
  FileSearchOutlined,
  PlusOutlined,
  SendOutlined,
} from '@ant-design/icons';
import { ModalForm, ProCard } from '@ant-design/pro-components';
import ProForm, {
  DrawerForm,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { ActionType } from '@ant-design/pro-table';
import { Button, Form, message } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddSubmitPreview from './AddSubmitPreview';
import UploadDragger from '../../../components/UploadDragger';
import TextEditor from '../../../components/TextEditor';

interface AddSubmitProps {
  topicId: string;
  topicName: string;
  onRefurbish: () => void;
}

const AddSubmit: React.FC<AddSubmitProps> = ({ topicId, topicName, onRefurbish }) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const formRef = useRef<ProFormInstance>();

  const [industrys, setIndustrysState] = useState<any[]>([]);

  const [openAddSubmit, setOpenAddSubmit] = useState<boolean>(false);

  const [openAddSubmitPreview, setOpenAddSubmitPreview] = useState<boolean>(false);
  const [previewData, setPreviewData] = useState<CuesSubmitBo.AddSubmitPreview>();

  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  const [green, setGreen] = useState<boolean>(false);

  /**
   * 加载权限详情
   * @param key
   */
  const getCuesIndustryData = async () => {
    try {
      const response = await listCuesIndustry();

      setIndustrysState(
        response.data.map((item) => {
          return { label: item.name, value: item.id };
        }),
      );
    } catch (error) { }
  };

  return (
    <DrawerForm
      key="drawer_form_add_submit"
      title="报送线索"
      drawerProps={{
        maskClosable: false,
        destroyOnClose: true,
        width: '100%',
      }}
      formRef={formRef}
      trigger={
        <Button key="button_add_submit" type="primary">
          <PlusOutlined />
          报送线索
        </Button>
      }
      initialValues={{}}
      visible={openAddSubmit}
      onVisibleChange={(visible) => {
        setOpenAddSubmit(visible);
        if (visible) {
          getCuesIndustryData();
        }
      }}
      layout="horizontal"
      submitter={{
        searchConfig: {
          submitText: (
            <>
              <FileSearchOutlined /> 预览
            </>
          ),
        },
        render: (props, defaultDoms) => {
          return [
            defaultDoms,
            <Button
              key="button_add_submit"
              icon={<SendOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              onClick={() => {
                /**
                 * ======================
                 * 直接发布
                 * ======================
                 */
                const values = formRef.current?.getFieldsValue();

                if (!(values.articleName !== undefined && values.articleName.length > 0)) {
                  message.warning('请输入标题');
                  return;
                }

                if (
                  !(values.articleIndustryIds !== undefined && values.articleIndustryIds.length > 0)
                ) {
                  message.warning('请选择至少一个行业');
                  return;
                }

                if (!(values.articleLabels !== undefined && values.articleLabels.length > 0)) {
                  message.warning('请输入至少一个标签');
                  return;
                }

                if (!(values.articleContent !== undefined && values.articleContent.length > 0)) {
                  message.warning('请输入线索内容');
                  return;
                }

                setModalFormOpenState(true);
              }}
            >
              提交
            </Button>,
            <AddSubmitPreview
              key="add_submit_preview"
              onSubmit={() => {
                setOpenAddSubmit(false);
                onRefurbish();
              }}
              open={openAddSubmitPreview}
              onVisibleChange={(open) => {
                setOpenAddSubmitPreview(open);
              }}
              details={previewData}
            />,
            <ModalForm
              key={'modal_form_add_submit'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  确认提交
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: '100%',
                destroyOnClose: true,
              }}
              visible={modalFormOpen}
              onVisibleChange={setModalFormOpenState}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async () => {
                const values = formRef.current?.getFieldsValue();

                if (
                  values.articleAttachments !== undefined &&
                  values.articleAttachments.length > 0
                ) {
                  const articleAttachments = values.articleAttachments.map(
                    (item: { response: { data: { id: any } } }) => {
                      return item.response.data.id;
                    },
                  );

                  values.articleAttachments = articleAttachments;
                }

                const response = await saveCuesSubmit({
                  topicId,
                  articleName: values?.articleName,
                  articleIndustryIds: values?.articleIndustryIds,
                  articleLabels: values?.articleLabels,
                  remarks: values?.remarks,
                  articleContent: values?.articleContent,
                  articleAttachments: values?.articleAttachments,
                  createdSource: 1,
                });

                if (response.code === 0) {
                  message.success('提交成功');
                  setOpenAddSubmit(false);
                  onRefurbish();
                  return true;
                } else {
                  return false;
                }
              }}
            />,
          ];
        },
      }}
      onFinish={async (values) => {
        /**
         * ======================
         * 预览发布
         * ======================
         */
        if (!(values.articleName !== undefined && values.articleName.length > 0)) {
          message.warning('请输入标题');
          return;
        }

        if (!(values.articleIndustryIds !== undefined && values.articleIndustryIds.length > 0)) {
          message.warning('请选择至少一个行业');
          return;
        }

        if (!(values.articleLabels !== undefined && values.articleLabels.length > 0)) {
          message.warning('请输入至少一个标签');
          return;
        }

        if (!(values.articleContent !== undefined && values.articleContent.length > 0)) {
          message.warning('请输入线索内容');
          return;
        }

        const articleIndustrys = values.articleIndustryIds?.map((item) => {
          const industry = industrys.find((e) => e.value === item);
          return industry;
        });

        setPreviewData({
          topicId: topicId,
          topicName: topicName,
          articleName: values.articleName,
          articleIndustrys: articleIndustrys,
          articleLabels: values.articleLabels,
          remarks: values.remarks,
          articleContent: values.articleContent,
          createdSource: 1,
          articleAttachments: values.articleAttachments,
        });

        setOpenAddSubmitPreview(true);
      }}
    >
      <ProFormText
        width="xl"
        name="articleName"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            标题
          </>
        }
        fieldProps={{
          allowClear: true,
          maxLength: 200,
        }}
      />

      <ProFormSelect
        width="xl"
        name="articleIndustryIds"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            行业
          </>
        }
        options={industrys}
        fieldProps={{
          mode: 'multiple',
          allowClear: true,

        }}
      />
      <Form.Item
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            标签
          </>
        }
        name="articleLabels"
        extra={
          <div
          >
            最少输入一个
          </div>
        }
      >
        <TagGroup />
      </Form.Item>
      <ProCard ghost>
        <ProCard colSpan={green ? '750px' : '1'} ghost>
          <ProForm.Item
            name="articleContent"
            label={
              <>
                <span
                  style={{
                    color: '#ff4d4f',
                    fontSize: 14,
                    paddingRight: 4,
                  }}
                >
                  *
                </span>
                线索内容
              </>
            }
          >
            <TextEditor
              onInit={(editor) => { }}
              readonly={false}
              onClick={(value) => { }}
              defaultContent=""
              tinyID="tinyId"
            // extra={
            //   <Button
            //     icon={<CoffeeOutlined />}
            //     key="btn_green_submit_preview"
            //     style={{
            //       background: '#87d068',
            //     }}
            //     type="primary"
            //     size="small"
            //     onClick={() => {
            //       setGreen(true);
            //     }}
            //   >
            //     审核
            //   </Button>
            // }
            />
          </ProForm.Item>
        </ProCard>

      </ProCard>
      <ProForm.Group>
        <ProFormTextArea
          name="remarks"
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              备注
            </span>
          }
          width="xl"
          fieldProps={{
            allowClear: true,
            rows: 2,
            maxLength: 200,
          }}
        />
      </ProForm.Group>
      <FormItem
        name="articleAttachments"
        hidden={!access.线索征集x上报线索x附件}
        label={
          <span
            style={{
              marginLeft: 11,
            }}
          >
            附件
          </span>
        }
      >
        <div
        >
          <UploadDragger
            onPreview={(file) => { }}
            access={{
              isPicture: access.线索征集x上报线索x附件x图片,
              isVideo: access.线索征集x上报线索x附件x视频,
              isOffice: access.线索征集x上报线索x附件x办公,
              isOther: access.线索征集x上报线索x附件x其他,
            }}
            url="/cues/attachment/save"
            mode="submit"
          />
        </div>
      </FormItem>
    </DrawerForm>
  );
};
export default AddSubmit;
